<template>
  <LoginBase title="账号登录">
    <a-form>
      <a-form-item>
        <a-input v-model:value="loginRequest.name" size="large" placeholder="用户名/手机号" />
      </a-form-item>
      <a-form-item>
        <a-input-password v-model:value="loginRequest.password" size="large" placeholder="密码" />
      </a-form-item>
      <a-form-item>
        <a-button size="large" block type="primary" :loading="loading" @click="onLogin">{{ loading ? '登录中...' : '登录' }}
        </a-button>
      </a-form-item>
      <a-form-item>
        <div style="text-align: center;">
          <router-link to="/user/register">账号注册</router-link>
          <a-divider type="vertical" />
          <router-link to="/user/resetpassword">忘记密码</router-link>
        </div>
      </a-form-item>
    </a-form>
  </LoginBase>
</template>
<script lang="ts" setup>
import { ref, withDefaults, defineProps } from "vue";
import LoginBase from "./LoginBase.vue";
import { useRouter } from 'vue-router'
import { message } from 'ant-design-vue';

import { UserService } from "@/services/User/UserService";
import { UserDto } from "@/models/User/UserDto";
import { UserContext } from "@/utils/UserContext";



const loginRequest = ref<UserDto.LoginRequest>(new UserDto.LoginRequest());
const loading = ref(false);
const _useRouter = useRouter();

/** 获取url地址中的参数 */
const props = withDefaults(defineProps<{ redirect: string }>(), { redirect: "" });
const redirect = props.redirect;

const onLogin = async () => {
  loading.value = true;
  let rs = await UserService.loginAsync(loginRequest.value);
  if (rs.code == 0) {
    UserContext.add(
      rs.data.Name,
      rs.data.Token,
      rs.data.User_Id
    );

    setTimeout(function () {
      if (redirect != null && redirect != "") {
        let path = decodeURIComponent(redirect);
        _useRouter.push(path);
      } else {
        _useRouter.push("/");
      }
      loading.value = false;
    }, 500);
  } else {
    message.error(rs.msg);
    loading.value = false;
  }
}
</script>
